import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 开启页面加载进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 获取登录token
  const hasToken = getToken()

  if (hasToken) { //  已经登录的情况下
    try {
      // console.log(store.getters.addrouters,'addrouters')
      if (store.getters.addrouters.length === 0) {
        // 获取用户权限
        const powers = await store.dispatch('user/getInfo')
        // 便是用户权限获取路由
        store.dispatch('permission/generateRoutes', powers).then(res => {
          // 动态添加路由
          router.addRoutes(res)
          next({ ...to, replace: true })
        })
      } else {
        next()
      }
    } catch (error) {
      // remove token and go to login page to re-login
      await store.dispatch('user/resetToken')
      Message.error(error || '')
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  } else { // 没登录时
    if (whiteList.indexOf(to.path) !== -1) { // 如果是去登录页面，则去
      next()
    } else { // 否则跳转到登录页面，并将登录后跳转地址带上
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})
